package cn.intotw.pp.decode;

import cn.intotw.pp.constants.Constant;
import cn.intotw.pp.entity.PPProtocolFrame;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author Chenxiang
 * @Description: 协议解码器，将字节流转换成协议帧
 * @create 2018/8/21 13:48
 */
public class PPProtocolDecoder extends ByteToMessageDecoder {
    private final int HEAD_LENGTH=4+4;
    private int frameMaxLength=2048;

    public PPProtocolDecoder(int frameMaxLength) {
        this.frameMaxLength = frameMaxLength;
    }

    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readableBytes() > HEAD_LENGTH)
        {
            if(byteBuf.readableBytes()>frameMaxLength)
            {
                byteBuf.skipBytes(byteBuf.readableBytes());
            }

            int beginReader;

            while (true)
            {
                beginReader=byteBuf.readerIndex();
                byteBuf.markReaderIndex();

                if(byteBuf.readInt() == Constant.PACKET_BEGIN)
                {
                    break;
                }

                byteBuf.resetReaderIndex();
                byteBuf.readByte();
                if(byteBuf.readableBytes() < HEAD_LENGTH)
                {
                    return;
                }
            }

            int length=byteBuf.readInt();
            if(byteBuf.readableBytes() < length)
            {
                byteBuf.readerIndex(beginReader);
                return ;
            }
            byte[] data=new byte[length];
            byteBuf.readBytes(data);
            PPProtocolFrame ppProtocolFrame=new PPProtocolFrame();
            ppProtocolFrame.setContentLength(length);
            ppProtocolFrame.setContent(data);
            list.add(ppProtocolFrame);
        }
    }
}